package com.zeros.latte.apps;

import com.joanzapata.iconify.IconFontDescriptor;
import com.joanzapata.iconify.Iconify;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.WeakHashMap;

/**
 * 通用初始化类 on 2018/1/26.
 */

public class Configurator {

    private static final HashMap<String, Object> LATTE_CONFIGS = new HashMap<>();   //因为这是初始化，所以其生命周期是全局，不能用WeakHashMap
    private static final ArrayList<IconFontDescriptor> ICONS = new ArrayList<>();


    /**
     * 1.初始化本类
     */
    public Configurator() {
        // 懒汉模式单例最好加双向锁
        LATTE_CONFIGS.put(ConfigType.CONFIG_READY.name(), false);
    }

    //    另一种单例--静态类
    private static class Holder {
        private static final Configurator INSTANCE = new Configurator();
    }

    public static Configurator getInstance() {
        return Holder.INSTANCE;
    }
//    单例End

//    获取此类状态
    final HashMap<String,Object> getLatteConfigs() {
        return LATTE_CONFIGS;
    }

    //    配置好后更改状态
    public final void configure() {
//        通用的东西在初始化时就配置好,如此处图标
        initIcons();
        LATTE_CONFIGS.put(ConfigType.CONFIG_READY.name(), true);
    }

    /**
     * 2.配置API-Host
     */
    public final Configurator withApiHost(String host) {
        LATTE_CONFIGS.put(ConfigType.API_HOST.name(), host);
        return this;
    }

    /**
     * 3.初始化icon类库
     */
    private void initIcons(){
        if (ICONS.size() > 0) {
            final Iconify.IconifyInitializer initializer = Iconify.with(ICONS.get(0));
            for (int i=1;i<ICONS.size();i++) {
                initializer.with(ICONS.get(i));
            }
        }
    }

//    添加自己图标
    public final Configurator withIcon(IconFontDescriptor descriptor) {
        ICONS.add(descriptor);
        return this;
    }


//    是否初始化完成--获取配置时调用
    private void checkConfiguration(){
        final boolean isReady = (boolean) LATTE_CONFIGS.get(ConfigType.CONFIG_READY.name());
        if (!isReady) {
            throw new RuntimeException("Configuration is not ready,call configure");
        }
    }

    @SuppressWarnings("unchecked")
    final <T> T getConfiguration(Enum<ConfigType> key) {
        checkConfiguration();
        return (T) LATTE_CONFIGS.get(key.name());
    }

}
